package org.xxpay.pay.channel.yiyunfu;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Maps;
import org.springframework.stereotype.Service;
import org.xxpay.common.http.UriVariables;
import org.xxpay.common.util.HtmlUtils;
import org.xxpay.common.util.sign.SignUtils;
import org.xxpay.common.util.str.StringUtils;
import org.xxpay.core.common.constant.PayConstant;
import org.xxpay.core.common.util.AmountUtil;
import org.xxpay.core.entity.PayOrder;
import org.xxpay.pay.channel.BasePayment;
import org.xxpay.pay.channel.xinanali.util.HttpClick;

import java.util.Map;

@Service
public class YiyunfuPaymentService extends BasePayment {

    private final static String logPrefix = "【易云付】";
    @Override
    public String getChannelName() {
        return YiyunfuConfig.CHANNEL_NAME;
    }
    /**
     * 支付下单
     * @param payOrder
     * @return
     */
    @Override
    public JSONObject pay(PayOrder payOrder){
        return doOrderReq(payOrder);
    }

    /**
     * 查询订单
     * @param payOrder
     * @return
     */
    @Override
    public JSONObject query(PayOrder payOrder){
        JSONObject retObj = buildRetObj();
        retObj.put(PayConstant.RETURN_PARAM_RETCODE, PayConstant.RETURN_VALUE_FAIL);
        retObj.put(PayConstant.RESULT_PARAM_ERRDES, "没有订单查询接口");
        return retObj;
    }

    //下单具体实现
    private JSONObject doOrderReq(PayOrder payOrder){
        YiyunfuConfig config = new YiyunfuConfig(getPayParam(payOrder));
        Map<String,Object> params = Maps.newHashMap();
        //设置参数
        setParams(payOrder,config,params);
        _log.info("{}请求数据:{}", getChannelName(), JSON.toJSONString(params));
        //将订单改为支付中
        rpcCommonService.rpcPayOrderService.updateStatus4Ing(payOrder.getPayOrderId(), null);
        String reslut=null;
        try {
            reslut = HttpClick.sendHttpPost(config.getRequestUrl()+YiyunfuConfig.REQ_PAY_URL_FIXX,JSON.toJSONString(params));
        } catch (Exception e) {
            e.printStackTrace();
        }
        JSONObject origin = JSONObject.parseObject(reslut);
        _log.info("{}响应数据:{}", getChannelName(), JSON.toJSONString(origin));
        // 响应对象
        JSONObject retObj = new JSONObject();
        if(StringUtils.equals("00",origin.getString("code"))){
            if(StringUtils.equals("ZFB",origin.getString("serviceType"))){
                String codeUrl = origin.getString("payInfo");

                Map queryMap = Maps.newHashMap();
                queryMap.put("codeUrl", codeUrl);
                queryMap.put("money", params.get("totalFee"));
                queryMap.put("orderNo", payOrder.getPayOrderId());
                queryMap.put("isJump",1);//1:不自动打开支付宝;0:自动打开支付;
                queryMap.put("isShow",0);//1:不自动显示;0:自动显示;
                String jumpUrl = payConfig.getPayUrl() + "/cashier/go?" + UriVariables.getMapToParameters(queryMap);
                return buildPayResultOfForm(retObj, payOrder, HtmlUtils.toJS(jumpUrl));
            }
            if(StringUtils.equals("ZFB_WAP",origin.getString("serviceType"))){
                return buildPayResultOfForm(retObj, payOrder,"<script type=\"text/javascript\">\n" +
                        "　　window.location.href=\""+ origin.getString("payInfo")+"\";\n" +
                        "　　</script>" );
            }
            if(StringUtils.equals("ZFB_H5",origin.getString("serviceType"))){
                return buildPayResultOfForm(retObj, payOrder,origin.getString("payInfo"));
            }
        }
        retObj.put(PayConstant.RETURN_PARAM_RETCODE, PayConstant.RETURN_VALUE_FAIL);
        retObj.put(PayConstant.RESULT_PARAM_ERRDES, origin.toJSONString());
        return retObj;
    }

    //设置请求参数
    private void setParams(PayOrder payOrder, YiyunfuConfig config,Map<String,Object> params){
        params.put("mchId", config.getAppId());
        params.put("outTradeNo", payOrder.getPayOrderId());
        params.put("callbackUrl", payConfig.getNotifyUrl(getChannelName()));
        params.put("totalFee", AmountUtil.convertCent2Dollar(String.valueOf(payOrder.getAmount())));
        params.put("goodsTag", payOrder.getPayOrderId());
        params.put("body", payOrder.getPayOrderId());
        params.put("service", config.getPayProduct());
        params.put("way", config.getPayMode());
        params.put("mchCreateIp", payOrder.getClientIp());
        params.put("sign", getSign(params, config.getPrivateKey()));
    }

    //获取sign
    private String getSign(Map<String,Object> params,String key){
        String signTxt = SignUtils.parameterText(params);
        _log.info("{}待签名字符串：{}", logPrefix, signTxt+"&key="+key);
        String sign = SignUtils.MD5.createSign(signTxt, "&key="+key, SignUtils.CHARSET_UTF8);
        return sign;
    }

}
